package cn.shopthrive.merchants;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.HashMap;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
  private static final String TAG = "MainActivity";
  private static final String WX_CHANNEL = "com.shopthrive.merchants/wechat";
  private static final String AGREEMENT_CHANNEL = "com.shopthrive.merchants/agreement";
  private static final String PUSH_CHANNEL = "com.shopthrive.merchants/push";
  private String notificationData;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handleIntent(getIntent());
  }

  @Override
  protected void onNewIntent(@NonNull Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    handleIntent(intent);
  }

  private void handleIntent(Intent intent) {
    if (intent == null) {
      Log.w(TAG, "Intent is null");
      return;
    }
    long messageId = intent.getLongExtra("vivo_push_messageId", -1);
    Log.i(TAG, "Message ID: " + messageId);

    Bundle extras = intent.getExtras();
    String route = null;
    String skipContent = null;
    int skipType = -1;
    HashMap<String, Object> params = new HashMap<>();
    if (extras != null) {
      for (String key : extras.keySet()) {
        if (!TextUtils.isEmpty(key)) {
          Object value = extras.get(key);
          String content = value == null ? "null" : value.toString();
          Log.i(TAG, "Extra: key=" + key + ", content=" + content);
          if ("route".equals(key)) {
            route = content;
          } else if ("skipContent".equals(key)) {
            skipContent = content;
          } else if ("skipType".equals(key)) {
            try {
              skipType = Integer.parseInt(content);
            } catch (NumberFormatException e) {
              Log.w(TAG, "Invalid skipType: " + content);
            }
          } else if (!"vivo_push_messageId".equals(key)) {
            params.put(key, content);
          }
        }
      }
    }

    MyApplication app = (MyApplication) getApplication();
    if (skipType == 2 && skipContent != null && skipContent.startsWith("http")) {
      app.openUrl(this, skipContent);
    } else if (route != null) {
      notificationData = route;
      HashMap<String, Object> data = new HashMap<>();
      data.put("route", route);
      data.put("params", params);
      data.put("skipType", skipType);
      app.notifyPushMessage(this, data);
    }
  }

  @Override
  public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    super.configureFlutterEngine(flutterEngine);

    MethodChannel weChatChannel = initWeChatChannel(flutterEngine);
    weChatChannel.setMethodCallHandler(
            (call, result) -> {
              Log.i(TAG, "[Channel: wechat] Method: " + call.method);
              switch (call.method) {
                case "isWeChatInstalled":
                  result.success(WeChatHelper.isWeChatInstalled());
                  break;
                case "login":
                  result.success(WeChatHelper.login());
                  break;
                default:
                  result.notImplemented();
                  break;
              }
            }
    );
    WeChatHelper.init(this, weChatChannel);
    // 用户同意协议
    MethodChannel agreementChannel = initAgreementChannel(flutterEngine);
    agreementChannel.setMethodCallHandler(
            (call, result) -> {
              Log.i(TAG, "[Channel: agreement] Method: " + call.method);
              if (call.method.equals("onAgreementChanged")) {
                boolean agreed = Boolean.TRUE.equals(call.argument("agreed"));
                String brand = call.argument("brand") != null ? call.argument("brand") : "vivo";
                MyApplication app = (MyApplication) getApplication();
                assert brand != null;
                app.initPush(this, brand, agreed);
                result.success(null);
              } else {
                result.notImplemented();
              }
            }
    );

    MethodChannel pushChannel = initPushChannel(flutterEngine);
    MyApplication app = (MyApplication) getApplication();
    app.setPushChannel(pushChannel);
    pushChannel.setMethodCallHandler(
            (call, result) -> {
              Log.i(TAG, "[Channel: push] Method: " + call.method);
              switch (call.method) {
                case "getInitialNotification":
                  result.success(notificationData);
                  notificationData = null;
                  break;
                case "requestPushToken":
                  String brand = call.argument("brand");
                  boolean forceRefresh = Boolean.TRUE.equals(call.argument("forceRefresh"));
                  if (brand == null) {
                    result.error("INVALID_BRAND", "Brand is required", null);
                    return;
                  }
                  app.requestPushToken(this, brand, forceRefresh);
                  result.success(null);
                  break;
                default:
                  result.notImplemented();
                  break;
              }
            }
    );
  }

  private MethodChannel initWeChatChannel(FlutterEngine flutterEngine) {
    return new MethodChannel(
            flutterEngine.getDartExecutor().getBinaryMessenger(),
            WX_CHANNEL
    );
  }

  private MethodChannel initAgreementChannel(FlutterEngine flutterEngine) {
    return new MethodChannel(
            flutterEngine.getDartExecutor().getBinaryMessenger(),
            AGREEMENT_CHANNEL
    );
  }

  private MethodChannel initPushChannel(FlutterEngine flutterEngine) {
    return new MethodChannel(
            flutterEngine.getDartExecutor().getBinaryMessenger(),
            PUSH_CHANNEL
    );
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    WeChatHelper.cleanup(this);
  }
}